package cn.edu.csust.cvs.management.support;

import io.minio.MinioClient;
import io.minio.errors.MinioException;
import io.minio.policy.PolicyType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @Auther: snail
 * @Date: 2021/2/1 00:30
 * @Description: 文件上传工具类
 */
@Component
public class FileUploadSupport {

    @Value("${minio.endpoint}")
    public String endpoint;

    @Value("${minio.bucket.video}")
    public String videoBucket;

    @Value("${minio.bucket.audio}")
    public String audioBucket;

    @Value("${minio.key.access}")
    public String accessKey;

    @Value("${minio.key.secret}")
    public String secretKey;

    /**
     * 上传视频文件
     * @param fileName
     * @param localVideoPath
     * @return
     */
    public String uploadVideo(String fileName,String localVideoPath){
        try {
            MinioClient minioClient = new MinioClient(endpoint, accessKey, secretKey);
            boolean isExist = minioClient.bucketExists(videoBucket);
            if(!isExist) {
                minioClient.makeBucket(videoBucket);
                minioClient.setBucketPolicy(videoBucket, "", PolicyType.READ_WRITE);
            }
            minioClient.putObject(videoBucket,fileName, localVideoPath);
        } catch(MinioException | IOException | InvalidKeyException | NoSuchAlgorithmException | XmlPullParserException e) {
            e.printStackTrace();
        }
        return endpoint + "/" + videoBucket + "/" + fileName;
    }

    /**
     * 上传音频文件
     * @param fileName
     * @param localVideoPath
     * @return
     */
    public String uploadAudio(String fileName,String localVideoPath){
        try {
            MinioClient minioClient = new MinioClient(endpoint, accessKey, secretKey);
            boolean isExist = minioClient.bucketExists(audioBucket);
            if(!isExist) {
                minioClient.makeBucket(audioBucket);
                minioClient.setBucketPolicy(audioBucket, "", PolicyType.READ_WRITE);
            }
            minioClient.putObject(audioBucket,fileName, localVideoPath);
        } catch(MinioException | IOException | InvalidKeyException | NoSuchAlgorithmException | XmlPullParserException e) {
            e.printStackTrace();
        }
        return endpoint + "/" + audioBucket + "/" + fileName;
    }

}
